"""
API网关路由服务
==============

基于RedFire框架的路由管理服务
负责路由配置管理和路由匹配
"""

import logging
from typing import Dict, Any, Optional, List

from redfire_framework.cache.service import CacheService
from redfire_framework.events.bus import EventBus

logger = logging.getLogger(__name__)


class RouteService:
    """
    路由服务
    
    负责：
    - 路由配置管理
    - 路由匹配逻辑
    - 路由缓存管理
    """
    
    def __init__(
        self,
        cache_service: Optional[CacheService] = None,
        event_bus: Optional[EventBus] = None,
        config: Optional[Dict[str, Any]] = None
    ):
        """
        初始化路由服务
        
        Args:
            cache_service: 缓存服务
            event_bus: 事件总线
            config: 配置信息
        """
        self.cache_service = cache_service
        self.event_bus = event_bus
        self.config = config or {}
        
        # 路由配置
        self.routes = self.config.get("routes", [])
        
        logger.info(f"Route service initialized with {len(self.routes)} routes")
    
    async def list_routes(self) -> List[Dict[str, Any]]:
        """
        列出所有路由配置
        
        Returns:
            List[Dict[str, Any]]: 路由列表
        """
        return [
            {
                "path": route["path"],
                "service_name": route["service_name"],
                "target_path": route.get("target_path", ""),
                "methods": route.get("methods", ["GET"]),
                "rate_limit": route.get("rate_limit", 100),
                "timeout": route.get("timeout", 30.0),
                "auth_required": route.get("auth_required", False),
                "priority": route.get("priority", 100),
                "metadata": route.get("metadata", {})
            }
            for route in self.routes
        ]
    
    async def find_route(self, path: str, method: str) -> Optional[Dict[str, Any]]:
        """
        查找匹配的路由
        
        Args:
            path: 请求路径
            method: HTTP方法
            
        Returns:
            Optional[Dict[str, Any]]: 路由信息
        """
        # 从缓存获取
        cache_key = f"route_match:{path}:{method}"
        if self.cache_service:
            cached_route = await self.cache_service.get(cache_key)
            if cached_route:
                return cached_route
        
        # 按优先级排序查找
        sorted_routes = sorted(self.routes, key=lambda r: r.get("priority", 100))
        
        for route in sorted_routes:
            if self._match_path(path, route["path"]) and method.upper() in route.get("methods", ["GET"]):
                route_info = dict(route)
                
                # 缓存匹配结果
                if self.cache_service:
                    await self.cache_service.set(cache_key, route_info, ttl=300)
                
                return route_info
        
        return None
    
    def _match_path(self, request_path: str, route_pattern: str) -> bool:
        """
        匹配路由路径
        
        Args:
            request_path: 请求路径
            route_pattern: 路由模式
            
        Returns:
            bool: 是否匹配
        """
        # 精确匹配
        if route_pattern == request_path:
            return True
        
        # 通配符匹配
        if route_pattern.endswith("/*"):
            prefix = route_pattern[:-2]
            return request_path.startswith(prefix)
        
        # 参数匹配 (简化版本)
        if "{" in route_pattern and "}" in route_pattern:
            # 这里应该实现更复杂的参数匹配逻辑
            # 暂时简化处理
            return False
        
        return False
    
    async def reload_routes(self) -> Dict[str, Any]:
        """
        重新加载路由配置
        
        Returns:
            Dict[str, Any]: 重载结果
        """
        try:
            # 重新加载配置
            self.routes = self.config.get("routes", [])
            
            # 清除路由缓存
            if self.cache_service:
                # 这里应该清除所有路由相关的缓存
                # 简化实现，实际应该有更精确的缓存清理
                pass
            
            # 发布路由重载事件
            if self.event_bus:
                await self.event_bus.publish("gateway.routes.reloaded", {
                    "routes_count": len(self.routes),
                    "timestamp": __import__("time").time()
                })
            
            logger.info(f"Routes reloaded: {len(self.routes)} routes")
            
            return {
                "status": "success",
                "routes_count": len(self.routes)
            }
            
        except Exception as e:
            logger.error(f"Failed to reload routes: {e}", exc_info=True)
            return {
                "status": "error",
                "error": str(e)
            }
    
    async def add_route(self, route_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        添加新路由
        
        Args:
            route_config: 路由配置
            
        Returns:
            Dict[str, Any]: 添加结果
        """
        try:
            # 验证路由配置
            required_fields = ["path", "service_name"]
            for field in required_fields:
                if field not in route_config:
                    raise ValueError(f"Missing required field: {field}")
            
            # 检查路径冲突
            for existing_route in self.routes:
                if existing_route["path"] == route_config["path"]:
                    raise ValueError(f"Route path already exists: {route_config['path']}")
            
            # 添加路由
            self.routes.append(route_config)
            
            # 发布路由添加事件
            if self.event_bus:
                await self.event_bus.publish("gateway.route.added", {
                    "route": route_config,
                    "timestamp": __import__("time").time()
                })
            
            logger.info(f"Route added: {route_config['path']}")
            
            return {
                "status": "success",
                "route": route_config
            }
            
        except Exception as e:
            logger.error(f"Failed to add route: {e}", exc_info=True)
            return {
                "status": "error",
                "error": str(e)
            }
    
    async def remove_route(self, path: str) -> Dict[str, Any]:
        """
        移除路由
        
        Args:
            path: 路由路径
            
        Returns:
            Dict[str, Any]: 移除结果
        """
        try:
            # 查找并移除路由
            route_to_remove = None
            for i, route in enumerate(self.routes):
                if route["path"] == path:
                    route_to_remove = self.routes.pop(i)
                    break
            
            if not route_to_remove:
                raise ValueError(f"Route not found: {path}")
            
            # 清除相关缓存
            if self.cache_service:
                # 清除该路由的缓存
                pass
            
            # 发布路由移除事件
            if self.event_bus:
                await self.event_bus.publish("gateway.route.removed", {
                    "route": route_to_remove,
                    "timestamp": __import__("time").time()
                })
            
            logger.info(f"Route removed: {path}")
            
            return {
                "status": "success",
                "route": route_to_remove
            }
            
        except Exception as e:
            logger.error(f"Failed to remove route: {e}", exc_info=True)
            return {
                "status": "error",
                "error": str(e)
            }
